<?php
header("Content-type:text/html; charset=utf-8");


$db = new PDO("mysql:host=localhost;dbname=test;charset=utf8", "root", "root");

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try {
    $pageNum = 10;
     $page = (int) $_GET['p'];

    $html_file = "p" . $page . '.html';
    if (file_exists($html_file) && filemtime($html_file) + 300 >= time()) {
        echo file_get_contents($html_file);
        exit();
    }


    $page = $page < 1 ? 1 : $page;

    $sql = 'select count(*) as num from news';
    $stmt = $db->query($sql);
    $rows = $stmt->fetch(PDO::FETCH_ASSOC);
    $pageTotal = (int) ceil($rows['num'] / $pageNum);
    if ($page > $pageTotal) {
        $page = $pageTotal;
    }
    $offset = ($page - 1) * $pageNum;

    $next  =  $page + 1 > $pageTotal ? $pageTotal : $page + 1; //下一页
    $prve  =  $page - 1 < 1 ? $page : $page - 1;               //上一页
    $flist =  $page = 1;
  
    $sql1 = 'select * from news limit ' . $offset . ', ' . $pageNum;
    $stmt = $db->query($sql1);

    $data = $stmt->fetchAll(2);
} catch (Exception $e) {
    var_export($e->getCode());
    var_export($e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <center>
        <h3>新闻列表</h3>
        <table border="2" >
           <tr>
             <td>ID</td>
             <td>新闻标题</td>
             <td>新闻内容</td>
             <td>添加时间</td>
             <td>修改时间</td>
             <td>操作</td>
           </tr> 
           
           <?php foreach ($data as $key => $value): ?>
        <tr>
            <td><?php echo $value['id']; ?></td>
            <td><?php echo $value['n_name']; ?></td>
            <td><?php echo $value['n_desc']; ?></td>
            <td><?php echo $value['addTime']; ?></td>
            <td><?php echo $value['upTime']; ?></td>
            <td><a href="del.php?id=<?php echo $value['id']; ?>">删除</a></td>
        </tr>
        <?php endforeach ?> 
        </table>

        <a href="lists.php?p=<?php echo $flist;?>">首页</a>
        <a href="lists.php?p=<?php echo $prve;?>">上一页</a>
        <a href="lists.php?p=<?php echo $next;?>">下一页</a>
        <a href="lists.php?p=<?php echo $pageTotal;?>">尾页</a>
    </center>
</body>
</html>

